const express = require('express');
const bodyParser = require('body-parser')

const app = express()

// 配置body-parser
// 只要加入了这个配置，则在req请求对象上会多出来一个属性：body
// 也就是说：你可以直接通过req.body来获取表单post请求数据了
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

// app.use(function (req, res) {
//   res.setHeader('Content-Type', 'text/plain')
//   res.write('you posted:\n')
//   res.end(JSON.stringify(req.body, null, 2))
// })

app.use('/public/', express.static('./public/'));
app.engine('html', require('express-art-template'));

const comments = [
    {
      name: '张三',
      message: '今天天气不错！',
      dateTime: '2015-10-16'
    },
    {
      name: '张三2',
      message: '今天天气不错！',
      dateTime: '2015-10-16'
    },
    {
      name: '张三3',
      message: '今天天气不错！',
      dateTime: '2015-10-16'
    },
    {
      name: '张三4',
      message: '今天天气不错！',
      dateTime: '2015-10-16'
    },
    {
      name: '张三5',
      message: '今天天气不错！',
      dateTime: '2015-10-16'
    }
]
app.get('/', function (req, res) {
    res.render('index.html', {
        comments: comments
    });
});

app.get('/post', function(req, res) {
    res.render('post.html');
});

// app.get('/pinglun', function(req, res) {
//     const comment = req.query;
//     comment.dateTime = '2021-07-28 00:00:00';
//     comments.unshift(comment);
//     res.redirect('/');
// });

app.post('/post', function(req, res) {
  console.log(req.body);
  const comment = req.body;
  comment.dateTime = '2021-07-28 00:00:00';
  comments.unshift(comment);
  res.redirect('/');
})



app.listen(3000, function() {
    console.log('port 3000');
})